/*
 * @Descripttion:
 * @version:
 * @Author: chenxf
 * @Date: 2022-11-25 17:10:36
 */
import { getAction, postAction, deleteAction } from '@api/manage'

/**
 * 接口地址
 */
export const jossApi = {
  baseUrlPrefix: uploadApiPath => `/${uploadApiPath}/base-url-prefix`,
  objectPath: uploadApiPath => `/${uploadApiPath}/object-paths`,
  objectPrefix: uploadApiPath => `/${uploadApiPath}/object-prefix`,
  deleteObject: uploadApiPath => `/${uploadApiPath}/delete-object`
}

/**
 * 返回Joss中间件访问地址前缀
 * 参数三选一
 * @param uploadApiPath 业务请求的地址前缀 eg: uc/upload-path
 * @param token UC-AUTH 颁发的token
 * @param jossToken Joss版本的token
 * @param signParam Joss提供的公钥密钥签名参数
 */
export const baseUrlPrefix = (uploadApiPath, { token, jossToken, signParam }) => {
  let params = {}
  if (token) {
    params = { token: token }
  } else if (jossToken) {
    params = { jossToken: jossToken }
  } else if (signParam) {
    params = signParam
  }
  return new Promise((resolve, reject) => {
    getAction(jossApi.baseUrlPrefix(uploadApiPath), params)
      .then(res => {
        resolve(res.data)
      })
      .catch(e => {
        reject(e)
      })
  })
}

/**
 * 获取多个对象地址前缀，返回列表
 * @param uploadApiPath 业务请求的地址前缀 eg: uc/upload-path
 * @param params 参数
 *        {
 *          "objectSize":"", 文件大小（必填）
 *          "contextType":"", 文件类型（必填）  eg: image/hpg
 *          "objectNameSuffix":"", 文件后缀名（必填）  eg: .jpg
 *          "etag":"",  文件MD5签名
 *        }
 */
export const objectPath = (uploadApiPath, params) => {
  return new Promise((resolve, reject) => {
    postAction(jossApi.objectPath(uploadApiPath), params)
      .then(res => {
        if (res.success) {
          resolve(res.result)
        } else {
          reject(res)
        }
      })
      .catch(e => {
        reject(e)
      })
  })
}

/**
 * 获取对象地址前缀，返回列表
 * @param uploadApiPath 业务请求的地址前缀 eg: uc/upload-path
 * @param params 参数
 *        [{
 *          "objectSize":"", 文件大小（必填）
 *          "contextType":"", 文件类型（必填）  eg: image/hpg
 *          "objectNameSuffix":"", 文件后缀名（必填）  eg: .jpg
 *          "etag":"",  文件MD5签名
 *        }]
 */
export const objectPrefix = (uploadApiPath, params) => {
  return new Promise((resolve, reject) => {
    postAction(jossApi.objectPrefix(uploadApiPath), params)
      .then(res => {
        if (res.success) {
          resolve(res.result)
        } else {
          reject(res)
        }
      })
      .catch(e => {
        reject(e)
      })
  })
}

export const deleteObject = (uploadApiPath, params) => {
  return new Promise((resolve, reject) => {
    deleteAction(jossApi.deleteObject(uploadApiPath), params)
      .then(res => {
        if (res.success) {
          resolve(res.result)
        } else {
          reject(res)
        }
      })
      .catch(e => {
        reject(e)
      })
  })
}
